package xin.yangshuai.activemqgeneral.jms.queue;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * JmsConsumer2
 *
 * @author shuai
 * @date 2020/6/21
 */
public class JmsConsumer2 {

    public static final String ACTIVEMQ_URL = "tcp://192.168.124.7:61616";
    public static final String QUEUE_NAME = "queue01";

    public static void main(String[] args) throws JMSException, IOException {

        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);

        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        MessageConsumer messageConsumer = session.createConsumer(session.createQueue(QUEUE_NAME));

//        while (true) {
////            TextMessage textMessage = (TextMessage) messageConsumer.receive();
//            TextMessage textMessage = (TextMessage) messageConsumer.receive(4000L);
//            if (textMessage != null) {
//                System.out.println("****消费者接收消息：" + textMessage.getText());
//            } else {
//                break;
//            }
//        }

        messageConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                if (message != null & message instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage) message;
                    try {
                        System.out.println("****消费者2接收消息-MessageListener：" + textMessage.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }

                }
            }
        });
        System.in.read();

        messageConsumer.close();
        session.close();
        connection.close();
    }
}
